import gobject

import asyncmanager

from net import network
from presence import ps
from util import config

class Engine:
    
    def __init__(self, iface, my_id, my_name, sender):
        p = ps.PresenceService(iface, config.PORTS['presence-out'], config.PORTS['presence-in'], my_id, my_name, standalone=False)

        am = asyncmanager.AsyncManager(iface, p)
        self.am = am
        am.connect('message-received', self.__on_message_received)
        if sender:
            url = config.APP_DIRS[config.AUDIO] + '/hello.wav'
            msg_type = config.AUDIO
            dests = ['receiver']
            
            am.send_message(url, msg_type, dests)

        network.start()
        
    def run(self):
        # start main application loop
        gobject.threads_init()
        network.start()
        gobject.MainLoop().run()

    def shutdown(self):
        self.am.shutdown()

    def __on_message_received(self, gobject, msg):
        print 'Received ',msg.header.fname


if __name__ == '__main__':
    import sys

    if len(sys.argv) < 6:
        print "Usage: python engine.py <iface> <my_id> <my_name> <sender?> <crosswire?>"

    iface, my_id, my_name, sender,crosswire = sys.argv[1:]
    if sender == 'True':
        sender = True
    else:
        sender = False

    if crosswire == 'True':
        crosswire = True
    else:
        crosswire = False
    if crosswire:
        if sender:
            config.PORTS = {
                'presence-out'  : 8000,
                'presence-in'   : 8001,
                'unicast-out'   : 8002,
                'unicast-in'    : 8003,
                'broadcast-out' : 8004,
                'broadcast-in'  : 8005,
                # ---
                'control-in'    : 8006,
            }
            #config.MEDIA_ROOT = '/home/camick/camick/memento/src/sender/'
        else:
            config.PORTS = {
                'presence-out'  : 8001,
                'presence-in'   : 8000,
                'unicast-out'   : 8003,
                'unicast-in'    : 8002,
                'broadcast-out' : 8005,
                'broadcast-in'  : 8004,
                # ---
                'control-in'    : 8007,
            }
           # config.MEDIA_ROOT = '/home/camick/camick/memento/src/sender/'

    config.CONTROL_PORT = config.PORTS['control-in']

    e = Engine(iface, my_id, my_name, sender)
    try:
        e.run()
    except KeyboardInterrupt:
        e.shutdown()



    
